/* Copyright (c) 2022, TD SYNNEX Corporation. All rights reserved */
const { removeTagReg } = require('../eason-webpack/Utils');
const templateReg = /\[\[[^\]]*\]\]/g

module.exports = function(htmlCode) {
  const matchList = htmlCode.match(templateReg);

  if(!matchList) return `
  export default function () {
    return \`${removeTagReg.exec(htmlCode)[0]}\`
  }
  `;

  return `
  export default function () {
    ${createMatchList(matchList)}
    return \`${createMatchCode(matchList, removeTagReg.exec(htmlCode)[0])}\`
  }
  `;
}

function createMatchList(matchList) {
  return matchList.map(item => `
    const ${createPrivateName(item)} = this.${createBaseName(item)} || ''
  `).join('\n')
}

function createMatchCode(matchList, code) {
  matchList.forEach(item => {
    code = code.replace(item, `\${${createPrivateName(item)}}`)
  })
  return code;
}

function createBaseName(item) {
  return item.replace(/[\]\[]/g, '')
}

function createPrivateName(item) {
  return item.replace(/[\]\[]/g, '').split('.').join('_')
}